/****************************************************************************
 *
 * Copyright (C) 2003-2010 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.dataset.snort;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nfse.NetFSERecord;
import nfse.NetFSEUtil;
import nfse.gui.record.FlexRecordField;
import nfse.gui.server.GUIRecordFactory;
import nfse.gui.server.RecordBuilderUtil;

public class SourcefireSyslogRecordFactory extends GUIRecordFactory<SourcefireSyslogRecord> {

    public SourcefireSyslogRecordFactory() {
        builder = new RecordBuilderUtil();
        builder.addColumn(null, "id", RecordBuilderUtil.BIGINT);
        RecordBuilderUtil.SQLField field = builder.addColumn("Start TS", "startts", RecordBuilderUtil.TIMESTAMP);
        field = builder.addColumn("Src IP", "srcip", RecordBuilderUtil.INET);
        field = builder.addColumn("Src Port", "srcport", RecordBuilderUtil.INTEGER);
        field.setSubtype(FlexRecordField.SUB_TYPE_PORT);
        field = builder.addColumn("Dst IP", "dstip", RecordBuilderUtil.INET);
        field = builder.addColumn("Dst Port", "dstport", RecordBuilderUtil.INTEGER);
        field.setSubtype(FlexRecordField.SUB_TYPE_PORT);
        field = builder.addColumn("Protocol", "protocol", RecordBuilderUtil.INTEGER);
        field.setSubtype(FlexRecordField.SUB_TYPE_PROTOCOL);
        field = builder.addColumn("SID", "sid", RecordBuilderUtil.INTEGER);
        field = builder.addColumn("CID", "cid", RecordBuilderUtil.INTEGER);
        field = builder.addColumn("Priority", "priority", RecordBuilderUtil.INTEGER);
        field = builder.addColumn("Classification", "classification", RecordBuilderUtil.VARCHAR, 255);
        field = builder.addColumn("Description", "description", RecordBuilderUtil.VARCHAR, 255);
    }

    @Override
    protected void setValues(SourcefireSyslogRecord record, int id) {
        int idx = -1;
        builder.setFieldValue(++idx, "" + id);
        builder.setFieldValue(++idx, "" + record.getStartTS());
        builder.setFieldValue(++idx, record.getSrcAddr());
        builder.setFieldValue(++idx, "" + record.srcPort);
        builder.setFieldValue(++idx, record.getDstAddr());
        builder.setFieldValue(++idx, "" + record.dstPort);
        builder.setFieldValue(++idx, "" + record.proto);
        builder.setFieldValue(++idx, "" + record.sid);
        builder.setFieldValue(++idx, "" + record.cid);
        builder.setFieldValue(++idx, "" + record.priority);
        builder.setFieldValue(++idx, NetFSEUtil.prepareValueForInsert(record.classification));
        builder.setFieldValue(++idx, NetFSEUtil.prepareValueForInsert(record.sigName));
    }

    /*
     * (non-Javadoc)
     * 
     * @see nfse.NetFSERecordFactory#generate(java.lang.String, int)
     */
    @Override
    public NetFSERecord generate() {
        return new SourcefireSyslogRecord();
    }
    
    @Override
    public boolean isSyslog() {
        return true;
    }

    @Override
    public NetFSERecord generate(String line, int sensor) {
        try {
            SourcefireSyslogRecord rec = new SourcefireSyslogRecord(sensor);
            // System.out.println(line);
            rec.setInitialString(line);
            line = line.trim();

            int idx1 = line.indexOf(";");
            int idx2 = line.indexOf(";", idx1 + 2);
            int colIdx = line.indexOf(":", idx2 + 15);

            String tsStr = line.substring(0, idx1);
            if (!tsStr.equals("-1")) {
                java.sql.Timestamp ts = new java.sql.Timestamp(Long.parseLong(tsStr) * 1000);
                rec.setStartTS(ts);
            } else {
                tsStr = line.substring(idx2, colIdx);
                java.sql.Timestamp ts = NetFSEUtil.timestampFromSyslog(tsStr);
                rec.setStartTS(ts);
                line = ts.getTime() / 1000 + line.substring(idx1);
                idx1 = line.indexOf(";");
                idx2 = line.indexOf(";", idx1 + 2);
                colIdx = line.indexOf(":", idx2 + 15);
            }

            line = line.substring(colIdx + 1).trim();
            Pattern p = Pattern
                    .compile("\\[(.*)\\]\\[(.*)\\]\\[([0-9:]+)\\] (.*) \\[Classification: (.*)\\] \\[Priority: (.*)\\] \\{(.*)\\} (.*)");
            Matcher m = p.matcher(line);
            boolean b = m.matches();
            if (b) {
                int count = m.groupCount();
                
                int idx = 1;
                String sensorStr = m.group(idx);
                String policy = m.group(++idx);
                String value = m.group(++idx);
                String[] values = value.split(":");
                rec.sid = Integer.parseInt(values[2]);
                rec.cid = Integer.parseInt(values[1]);
                rec.sigClassID = Integer.parseInt(values[0]);

                rec.sigName = m.group(++idx);
                rec.classification = m.group(++idx);
                rec.priority = Integer.parseInt(m.group(++idx).trim());

                value = m.group(++idx);
                if (value.startsWith("{")) {
                    rec.proto = NetFSEUtil.getProtocol(value.substring(1, value.length() - 1));
                } else {
                    rec.proto = NetFSEUtil.getProtocol(value);
                }

                values = m.group(++idx).split(" ");
                String srcIP = "";
                int srcPort = -1;
                String[] srcValues = values[0].split(":");
                if (srcValues.length <= 1) {
                    srcIP = values[0];
                } else {
                    srcIP = srcValues[0];
                    srcPort = Integer.parseInt(srcValues[1]);
                }
                rec.setSrcAddr(srcIP);
                rec.srcPort = srcPort;

                String dstIP = "";
                int dstPort = -1;
                String[] dstValues = values[2].split(":");
                if (dstValues.length <= 1) {
                    dstIP = values[2];
                } else {
                    dstIP = dstValues[0];
                    dstPort = Integer.parseInt(dstValues[1]);
                }
                rec.dstPort = dstPort;

                rec.setSrcIP(NetFSEUtil.convertIPtoLong(srcIP));
                rec.setDstIP(NetFSEUtil.convertIPtoLong(dstIP));

            } else {
                rec.setTimestamp(null);
            }
            
            //System.out.println(rec);

            if (rec.getTimestamp() == null)
                return null;
            else
                return rec;

        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

}
